#include "iic_8624.h"

int iic_8624_init(XIicPs *InstancePtr, u16 DeviceId)
{
	int Status;
	XIicPs_Config *Config;

	/*
	 * Initialize the IIC driver so that it's ready to use
	 * Look up the configuration in the config table,
	 * then initialize it.
	 */
	Config = XIicPs_LookupConfig(DeviceId);
	if (NULL == Config) {
		return XST_FAILURE;
	}
	Status = XIicPs_CfgInitialize(InstancePtr, Config, Config->BaseAddress);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Perform a self-test to ensure that the hardware was built correctly.
	 */
	Status = XIicPs_SelfTest(InstancePtr);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Set the IIC serial clock rate.
	 */
	XIicPs_SetSClk(InstancePtr, IIC_SCLK_RATE);
	
	
	return XST_SUCCESS;
}

int iic_8624_read(XIicPs *InstancePtr, u8 *SendBuffer, u8 *RecvBuffer)
{
	int Status;
	
	Status = XIicPs_MasterSendPolled(InstancePtr, SendBuffer, 4, IIC_SLAVE_ADDR);

	if (Status != XST_SUCCESS)
	{
		return XST_FAILURE;
	}

	/*
	 * Wait until bus is idle to start another transfer.
	 */
	while (XIicPs_BusIsBusy(InstancePtr))
	{
	}
	Status = XIicPs_MasterRecvPolled(InstancePtr, RecvBuffer, 4, IIC_SLAVE_ADDR);
	if (Status != XST_SUCCESS)
	{
		return XST_FAILURE;
	}
	return XST_SUCCESS;
}


int iic_8624_write(XIicPs *InstancePtr, u8 *SendBuffer)
{
	int Status;
	
	Status = XIicPs_MasterSendPolled(InstancePtr, SendBuffer, 8, IIC_SLAVE_ADDR);
	if (Status != XST_SUCCESS) 
	{
		return XST_FAILURE;
	}
	while (XIicPs_BusIsBusy(InstancePtr))
	{
	}
	return XST_SUCCESS;
}
